package HibernateOrederManagement.app;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import HibernateOrderManagerment.bean.OrderItem;
import HibernateOrderManagerment.bean.Orders;
import HibernateOrderManagerment.bean.StoreGoods;


public class OrderItemDao {
	private Session session;
	
	public OrderItemDao(Session session){
		this.session=session;
	}
	
	public List<OrderItem> list(){
		Query<OrderItem> query=session.createQuery("from OrderItem",OrderItem.class);
		
		return query.getResultList();
	}
	
	public OrderItem getOrderItemById(long id){
		return session.get(OrderItem.class,id);
	}
	
	public OrderItem getByAmount(int amount){
		Query<OrderItem> query =session.createQuery("from OrderItem where amount=:amount",OrderItem.class);
		query.setParameter("amount",amount);
		return query.getSingleResult();
	}
	public OrderItem  getByStoreGoodsId(long id){
		StoreGoodsDao dao=new StoreGoodsDao(session);
		StoreGoods storeGoods =dao.getStoreGoodsById(id);
		Query<OrderItem> query =session.createQuery("from OrderItem where storeGoods=:storeGoods",OrderItem.class);
		query.setParameter("storeGoods", storeGoods);
		return query.getSingleResult();
	}
	public OrderItem getByOrdersId(long id){
		OrdersDao dao =new OrdersDao(session);
		Orders orders =dao.getOrdersById(id);
		Query<OrderItem> query =session.createQuery("from OrderItem where orders=:orders",OrderItem.class);
		query.setParameter("id", orders);
		return query.getSingleResult();
	}

	public void insert(OrderItem orderItem) {
		Transaction tx = session.beginTransaction();
		try {

			session.save(orderItem);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
	}
	public void update(OrderItem orderItem){
		Transaction tx = session.beginTransaction();
		try {

			session.update(orderItem);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
		
	}
	public void delete(OrderItem orderItem){
		Transaction tx = session.beginTransaction();
		try {
			
			session.delete(orderItem);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
		
	}

}
